﻿using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Mbs.Utils
{
    public class EasyHttpHelper
    {


        /// <summary>
        /// HTTP Post
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="postDataStr">json格式的数据</param>
        /// <returns></returns>
        public static string HttpPost(string Url, string postDataStr)
        {
            try
            {


                WebRequest request = WebRequest.Create(Url);
                request.Method = "POST";
                request.ContentType = "application/json";
                byte[] buf = Encoding.UTF8.GetBytes(postDataStr);
                byte[] byteArray = System.Text.Encoding.Default.GetBytes(postDataStr);
                request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
                request.GetRequestStream().Write(buf, 0, buf.Length);
                WebResponse response = request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
                return retString;
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// HTTP Get
        /// </summary>
        /// <param name="Url"></param>
        /// <returns></returns>
        public static string HttpGet(string Url)
        {
            try
            {

                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(Url);
                httpWebRequest.Method = "GET";
                httpWebRequest.ContentType = "text/html;charset=UTF-8";
                string text = "";
                using (WebResponse response = httpWebRequest.GetResponse())
                {
                    Stream responseStream = response.GetResponseStream();
                    byte[] array = new byte[40960];
                    for (; ; )
                    {
                        int num = responseStream.Read(array, 0, array.Length);
                        bool flag = num <= 0;
                        if (flag)
                        {
                            break;
                        }
                        text += Encoding.UTF8.GetString(array, 0, num);
                    }
                }
                return text;
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }
        /// <summary>
        /// 将数据及图片信息上传到服务器
        /// </summary>
        /// <param name="url"></param>
        /// <param name="filePath"></param>
        /// <param name="data">json格式的数据</param>
        public static async Task<string> HttpPostImage(string url, string filePath, string data)
        {
            try
            {

                filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filePath);
                var client = new HttpClient();
                var request = new HttpRequestMessage(HttpMethod.Post, url);
                var content = new MultipartFormDataContent();
                content.Add(new StreamContent(File.OpenRead(filePath)), "file", filePath);
                content.Add(new StringContent(data), "data");
                request.Content = content;
                var response = await client.SendAsync(request);
                response.EnsureSuccessStatusCode();

                return await response.Content.ReadAsStringAsync();
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }


        /// <summary>
        /// HttpGET
        /// </summary>
        /// <param name="url"></param>
        /// <param name="queryParameters"></param>
        /// <returns></returns>
        public async Task<string> HttpGetAsync(string url, object queryParameters)
        {
            using (var httpClient = new HttpClient())
            {
                try
                {
                    if (queryParameters != null)
                    {
                        // 将查询参数序列化为JSON字符串  
                        string json = JsonConvert.SerializeObject(queryParameters);
                        // 将JSON字符串添加到URL的查询字符串中  
                        if (!url.Contains("?"))
                        {
                            url += "?json=" + Uri.EscapeDataString(json);
                        }
                        else
                        {
                            url += "&json=" + Uri.EscapeDataString(json);
                        }
                    }

                    HttpResponseMessage response = await httpClient.GetAsync(url);
                    response.EnsureSuccessStatusCode();
                    return await response.Content.ReadAsStringAsync();
                }
                catch (Exception)
                {
                    return string.Empty;
                }
            }
        }

        /// <summary>
        /// POST提交
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postDataStr"></param>
        /// <returns></returns>
        public static async Task<string> HttpPostAsync(string url, string postDataStr)
        {
            using (var httpClient = new HttpClient())
            {
                try
                {
                    // 设置请求内容  
                    var content = new StringContent(postDataStr, Encoding.UTF8, "application/json");
                    // 发送POST请求  
                    HttpResponseMessage response = await httpClient.PostAsync(url, content);
                    // 确保请求成功  
                    response.EnsureSuccessStatusCode();
                    // 读取响应内容  
                    string responseBody = await response.Content.ReadAsStringAsync();
                    return responseBody;
                }
                catch (Exception)
                {
                    return string.Empty;
                }
            }
        }


        /// <summary>
        /// POST提交
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postDataStr"></param>
        /// <returns></returns>
        public static async Task<T> HttpPostAsyncSafe<T>(string url, string postDataStr)
        {
            using (var httpClient = new HttpClient())
            {
                try
                {
                    // 设置请求内容  
                    var content = new StringContent(postDataStr, Encoding.UTF8, "application/json");
                    // 发送POST请求  
                    HttpResponseMessage response = await httpClient.PostAsync(url, content);
                    // 确保请求成功  
                    response.EnsureSuccessStatusCode();
                    // 读取响应内容  
                    string responseBody = await response.Content.ReadAsStringAsync();
                    // 检查responseBody是否为null或空字符串  
                    if (string.IsNullOrEmpty(responseBody))
                    {
                        return default(T);
                    }
                    //Response<T> result = JsonConvert.DeserializeObject<Response<T>>(responseBody);
                    T result = JsonConvert.DeserializeObject<T>(responseBody);
                    if (result != null)
                    {
                        return result;
                    }
                    return default(T);
                }
                catch (Exception ex)
                {
                    return default(T);
                }
            }
        }

        //public static async Task<T> HttpPostAsync<T>(string url, string postDataStr)
        //{
        //    // 创建一个 HttpClientHandler 并设置自定义证书验证回调  
        //    var handler = new HttpClientHandler();
        //    handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; }; // 总是接受证书  

        //    using (var httpClient = new HttpClient(handler)) // 使用自定义的 handler 创建 HttpClient  
        //    {
        //        try
        //        {
        //            // 设置请求内容    
        //            var content = new StringContent(postDataStr, Encoding.UTF8, "application/json");

        //            // 发送POST请求    
        //            HttpResponseMessage response = await httpClient.PostAsync(url, content);

        //            // 确保请求成功    
        //            response.EnsureSuccessStatusCode();

        //            // 读取响应内容    
        //            string responseBody = await response.Content.ReadAsStringAsync();

        //            // 检查responseBody是否为null或空字符串    
        //            if (string.IsNullOrEmpty(responseBody))
        //            {
        //                return default(T);
        //            }

        //            Response<T> result = JsonConvert.DeserializeObject<Response<T>>(responseBody);

        //            if (result != null && result.code == 200)
        //            {
        //                return result.result;
        //            }

        //            return default(T);
        //        }
        //        catch (Exception ex)
        //        {
        //            // 在这里，您可以根据需要记录异常或进行其他错误处理  
        //            return default(T);
        //        }
        //    }
        //}

        public static async Task<T> HttpPostAsync<T>(string url, string postDataStr, int timeout = 30)
        {
            // 创建一个 HttpClientHandler 并设置自定义证书验证回调
            var handler = new HttpClientHandler();
            handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; }; // 总是接受证书
            using (var httpClient = new HttpClient(handler)) // 使用自定义的 handler 创建 HttpClient
            {
                // **添加超时设置**
                httpClient.Timeout = TimeSpan.FromSeconds(timeout);
                try
                {
                    // 设置请求内容
                    var content = new StringContent(postDataStr, Encoding.UTF8, "application/json");
                    // 发送POST请求
                    HttpResponseMessage response = await httpClient.PostAsync(url, content);
                    // 确保请求成功
                    response.EnsureSuccessStatusCode();
                    // 读取响应内容
                    string responseBody = await response.Content.ReadAsStringAsync();
                    // 检查responseBody是否为null或空字符串
                    if (string.IsNullOrEmpty(responseBody))
                    {
                        return default(T);
                    }
                    //Response<T> result = JsonConvert.DeserializeObject<Response<T>>(responseBody);
                    T result = JsonConvert.DeserializeObject<T>(responseBody);
                    if (result != null)
                    {
                        return result;
                    }
                    return default(T);
                }
                catch (TaskCanceledException ex) // 捕获超时异常
                {
                    // 处理超时异常
                    Console.WriteLine($"请求超时: {ex.Message}"); // 建议使用日志记录
                    return default(T);
                }
                catch (Exception ex)
                {
                    // 在这里，您可以根据需要记录异常或进行其他错误处理
                    Console.WriteLine($"请求发生异常: {ex.Message}");  // 建议使用日志记录
                    return default(T);
                }
            }
        }
    }
}

